'use strict'
import {fetchBanner, hotClass, query} from "../services/homeService";
import {host} from '../constants/Host'

export default {

  namespace: 'home',

  state: {
    city: [],
    banners: [],        //轮播图
    hotClasses: [],
    pagination: {},
  },

  subscriptions: {
    setup({dispatch, history}) {  // eslint-disable-line
    },
  },

  effects: {
    //拉取轮播图
    * search({val}, {call, put}) {
      const res = yield call(_ => query(val));
      yield put({type: 'save', res});
    },
    //拉取轮播图
    * fetchBanner(obj, {call, put}) {
      const {data} = yield call(_ => fetchBanner());
      data.sort(({orderid: sa = 0}, {orderid: sb = 0}) => {
        return sa - sb;
      });
      yield put({type: 'banners', payload: data.map(({img, ...obj}) => ({img: `${host}/${img}`, ...obj}))});
    },
    //热门课程
    * fetchHotClass({body}, {call, put}) {
      const {data = {}} = yield call(_ => hotClass(body)) || {};
      const {
        data: hotClasses = [],
        page = 0,
        pageSize = 0,
        total = 0,
        totalPage = 0
      } = data;
      const pagination = {page, pageSize, total, totalPage};
      yield put({type: 'hotClasses', data: hotClasses, pagination});
    },
  },

  reducers: {
    city(state = {}, {city = []}) {
      return {...state, city};
    },
    banners(state = {}, {payload = {}}) {
      return {...state, banners: payload};
    },
    hotClasses({hotClasses, ...state}, {data, pagination}) {
      return {...state, hotClasses: [...hotClasses, ...data], pagination};
    },
  },
};
